<?php
/**
 * Простой форум
 *
 * @author tonatos
 */
class c_comment_controller extends c_base_controller {

    public $user_id;

    public $is_admin;
    public $admin_usergroup = "Модераторы";
    public $is_user;


    public function __construct() {
        global $modx;        
        parent::__construct();

        //Пока используем стили форума
        $modx->regClientCSS("assets/snippets/mvc/data/forum/style.css");

        $this->user_id = $modx->getLoginUserID();
        if (!empty($this->user_id)){
            $this->is_user = true;            
            $this->is_admin = $modx->isMemberOfWebGroup(array($this->admin_usergroup));
        }else{
            $this->is_user = false;
        }
        $this->id_content = $modx->documentIdentifier;
    }


    /**
     *
     * @global DocumentParser $modx
     * @global c_mvc_util $mvc
     * @param <type> $params
     */
    public function index($params){
        global $modx,$mvc;

        if (empty($this->id_content)) return;

        $form = new c_form_controller();
        $form->add_antispam();
        $form->add_text("message","Комментарий","",1);
        $form->action = $modx->makeUrl($this->id_content)."#last";

        //Только аторизованные пользователи могут оставлять сообщения
        if ($this->is_user){

            if ($form->data_submitted()) {
                if ($form->is_validate()) {
                    $data = $form->get_data();

                    $model = new c_comment_model($data);
                    $model->id_content = $this->id_content;
                    $model->save();

                    //$this->notify_subscribers($model);

                    //$this->notify_admins($this->topic,$model);

                    $this->redirect($form->action);
                }
            }
        }

        //Показываем удаленные записи 15 минут после удаления
        $del_min = time() - 60*15;

        $posts = $modx->db->get_records("comment","(deleted=0 or deleted>$del_min) and id_content = $this->id_content","createdon");

        $this->post_count = count($posts);
        $user_ids = array();

        foreach($posts as $post){
            $user_ids[$post->user_id] = $post->user_id;
        }

        $users = array();
        foreach($user_ids as $user_id){
            $users[$user_id] = new c_web_users_model($user_id);
        }

        foreach ($posts as $post) {
            $post->user = $users[$post->user_id];
        }

        $this->posts = $posts;
        $this->form = $form;
        
        $this->show("index");
    }


    public function edit($params){
        global $modx;
        $id = (int)$params[2];

        if (empty($id)){
            $this->redirect($this->id_content);
        }

        //Отправляем на вход на сайт
        if (!$this->is_user){
            $cabinet = new c_workplace_controller();
        }

        $post = new c_comment_model($id);



        if (!$this->is_admin){
            $this->redirect($this->id_content);
        }

        $this->set_modx_field("pagetitle", "Изменить сообщение");

        //$this->add_modx_menu("Форум",$this->forum_page);
        $this->add_modx_menu("Изменить сообщение");



        $form = new c_form_controller();
        $form->add_antispam();
        $form->add_text("message","Комментарий","",1);

        $form->add_cancel($modx->makeUrl($this->id_content)."#post_$post->id");
        


        if ($form->data_submitted()) {
            if ($form->is_validate()) {
                $data = $form->get_data();

                $model = new c_comment_model($id);
                $model->message = $data['message'];
                $model->save();
                $this->redirect($modx->makeUrl($this->id_content)."#post_$post->id");

            }
        }else{
            $model = new c_comment_model($id);
            $form->set_data($model);
        }

        $form->show_form();
    }


    public function restore($params){
        global $modx;
        $id = (int)$params[2];

        //Отправляем на вход на сайт
        if (!$this->is_user){
            $cabinet = new c_workplace_controller();
        }

        if (!empty($id) && $this->is_admin){
            $model = new c_comment_model($id);
            $model->deleted = 0;
            $model->save();
            $this->redirect($modx->makeUrl($this->id_content)."#post_$id");
        }
        $this->redirect($this->id_content);

    }

    /**
     * Преобразование в html сущности, перевод строки в br
     * и автогенерация ссылок
     *
     * @param string $str
     * @return string
     */
    public function auto_convert($str){
        $in=array(
            '`((?:https?|ftp)://\S+[[:alnum:]]/?)`si',
            '`((?<!//)(www\.\S+[[:alnum:]]/?))`si',
            "#((?<!//))([a-z0-9\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i"
        );
        $out=array(
            '<a href="$1" target="_blank">$1</a> ',
            '<a href="http://$1" target="_blank">$1</a>',
            "\\1<a href=\"mailto:\\2@\\3\" class=orange>\\2@\\3</a>"
        );
        return nl2br(preg_replace($in,$out,htmlspecialchars($str)));
    }


    public function wrap($str){

        if (mb_strlen($str)>250){
            $arrs = explode(" ",$str);
            $result = "";
            foreach($arrs as $word){
                $result.=$word." ";
                if (mb_strlen($result)>180){
                    return $result." ...";
                }
            }
        }
        return $str;
    }

    public function delete($params){

        $id = (int)$params[2];

        //Отправляем на вход на сайт
        if (!$this->is_user){
            $cabinet = new c_workplace_controller();
        }


        if (!empty($id) && $this->is_admin){
            $model = new c_comment_model($id);
            $model->deleted = time();
            $model->save();
            $this->redirect($this->id_content);
        }
        $this->redirect($this->id_content);
    }


}
?>
